package com.yonyougov.devops.cruxcisupport.k8s.secret;

import com.yonyougov.devops.cruxcisupport.k8s.K8sRepository;
import com.yonyougov.devops.cruxcisupport.k8s.error.K8sConfIgNotFindException;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.springframework.stereotype.Repository;

@Repository
public class SecretRepositoryImpl implements SecretRepository {
    private final K8sRepository k8sRepository;

    public SecretRepositoryImpl(K8sRepository k8sRepository) {
        this.k8sRepository = k8sRepository;
    }

    @Override
    public Secret createOrReplace(SecretRequest secretRequest) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(secretRequest.getNameSpace());
        Secret result = null;
        try {
            Secret secret = new SecretBuilder().
                    withKind("Secret").
                    withNewMetadata().withName(secretRequest.getName()).endMetadata().
                    addToData(secretRequest.getData()).
                    withType("kubernetes.io/dockerconfigjson").
                    build();
            Secret oldSecret = client.secrets().inNamespace(secretRequest.getNameSpace()).withName(secretRequest.getName()).get();
            if (null != oldSecret) {
                client.secrets().inNamespace(secretRequest.getNameSpace()).withName(secretRequest.getName()).delete();
            }
            result = client.secrets().inNamespace(secretRequest.getNameSpace()).create(secret);

        } finally {
            client.close();
        }
        return result;
    }

    @Override
    public Secret get(String name, String nameSpace) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        Secret result = null;
        try {
            result = client.secrets().inNamespace(nameSpace).withName(name).get();
        } finally {
            client.close();
        }
        return result;
    }

    @Override
    public boolean delete(String secretName, String nameSpace) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);

        return client.secrets().inNamespace(nameSpace).withName(secretName).delete();

    }


}
